package cn.roylion.resilience4j.config;

import cn.roylion.resilience4j.core.Resilience4JRateLimiter;
import cn.roylion.resilience4j.core.Resilience4JRateLimiterProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.support.ConfigurationService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

/**
 * 路由限流配置
 *
 * @author tasher
 * @date 2021/7/8
 */
@ConditionalOnProperty(prefix = "resilience4j.enable", matchIfMissing = true)
@Configuration
@EnableConfigurationProperties(Resilience4JRateLimiterProperties.class)
public class RateLimiterConfiguration {

    @Bean
    public Resilience4JRateLimiter resilience4JRateLimiter(Resilience4JRateLimiterProperties properties, ConfigurationService configurationService) {
        return new Resilience4JRateLimiter(properties, configurationService);
    }

    @Bean
    public KeyResolver userKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }
}
